package com.jd.ymcc.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.jd.ymcc.SearchDoc;
import static com.jd.ymcc.constants.MqConstants.*;
import com.jd.ymcc.domain.*;
import com.jd.ymcc.dto.CourseDto;
import com.jd.ymcc.dto.MessageSmsDto;
import com.jd.ymcc.dto.UserIdSmsDto;
import com.jd.ymcc.enums.GlobalErrorCode;
import com.jd.ymcc.feigin.CourseEsFeign;
import com.jd.ymcc.mapper.CourseMapper;
import com.jd.ymcc.mapper.CourseTypeMapper;
import com.jd.ymcc.service.*;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.jd.ymcc.until.AssertUtil;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author director
 * @since 2022-09-30
 */
@Service
public class CourseServiceImpl extends ServiceImpl<CourseMapper, Course> implements ICourseService {


    @Autowired
    private ITeacherService teacherService;
    @Autowired
    private ICourseDetailService courseDetailService;
    @Autowired
    private ICourseMarketService courseMarketService;
    @Autowired
    private ICourseResourceService courseResourceService;
    @Autowired
    private ICourseSummaryService courseSummaryService;
    @Autowired
    private CourseMapper courseMapper;
    @Autowired
    private CourseTypeMapper courseTypeMapper;
    @Autowired
    private CourseEsFeign courseEsFeign;
    @Autowired
    private RocketMQTemplate rocketMQTemplate;
    @Override
    public void save(CourseDto courseDto) {
        //1.获取前端传入的对象
        Course course = courseDto.getCourse();
        CourseDetail courseDetail = courseDto.getCourseDetail();
        CourseMarket courseMarket = courseDto.getCourseMarket();
        CourseResource courseResource = courseDto.getCourseResource();
        List<Long> teacharIds = courseDto.getTeacharIds();
        //2.校验课程是否重复
        Course courseName = selectByName(course.getName());
        AssertUtil.isNull(courseName,GlobalErrorCode.NULL);
        //3.先保存课程，生成主键id，在保存其他表
        Long courseId = saveCourse(course, teacharIds);

        //4.保存详情表
        courseDetail.setId(courseId);
        courseDetailService.insert(courseDetail);
        //5.保存市场表
        courseMarket.setId(courseId);
        courseMarketService.insert(courseMarket);
        //6.保存资源表
        courseResource.setCourseId(courseId);
        courseResourceService.insert(courseResource);
        //7.保存课程中间表
        CourseSummary courseSummary = new CourseSummary();
        courseSummary.setId(courseId);
        courseSummaryService.insert(courseSummary);
        //8.保存老师中间表
        courseMapper.insertCourseTeacher(courseId,teacharIds);
        //9.在课程类型数量添加
        courseTypeMapper.updateTotalCountById(course.getCourseTypeId());
    }

    /**
     * 上架
     * @param id
     */
    @Override
    public void onLineCourse(Long id) {
        //1.通过过id获取课程消息
        Course course = selectById(id);
        AssertUtil.isNotNull(course,GlobalErrorCode.NULL);
        //2.修改上架状态,
        //2.1判断是否上架
        Boolean boo1 = course.getStatus() == Course.STATUS_ONLINE_NUMBER;
        AssertUtil.isFalse(boo1,GlobalErrorCode.ERROR_ONLINE);
        course.setStatus(Course.STATUS_ONLINE_NUMBER);
        //4.1将修改后的course保存
        updateById(course);
        //3.查询出跟doc对象相关的参数
        CourseMarket courseMarket = courseMarketService.selectById(id);
        CourseSummary courseSummary = courseSummaryService.selectById(id);
        CourseType courseType = courseTypeMapper.selectById(course.getCourseTypeId());
        //4.保存到doc中
        SearchDoc searchDoc = new SearchDoc();
        BeanUtils.copyProperties(course,searchDoc);
        BeanUtils.copyProperties(courseMarket,searchDoc);
        BeanUtils.copyProperties(courseSummary,searchDoc);
        searchDoc.setCourseTypeName(courseType.getName());

        //5.将doc获取的上架消息存入到ES中
        courseEsFeign.saveCourseEs(searchDoc);
        //6.上架后发送消息
        sendSmsMessage(course);
    }

    /**
     * 下架
     * @param id
     */
    @Override
    public void offLineCourse(Long id) {
        //1.通过过id获取课程消息
        Course course = selectById(id);
        AssertUtil.isNotNull(course,GlobalErrorCode.NULL);
        //2.修改上架状态,
        //2.1判断是否下架
        Boolean boo1 = course.getStatus() == Course.STATUS_NO_NUMBER;
        AssertUtil.isFalse(boo1,GlobalErrorCode.ERROR_ONLINE);
        course.setStatus(Course.STATUS_NO_NUMBER);
        //4.1将修改后的course保存
        updateById(course);
    }

    /**
     * 上架发送消息
     * @param course
     */
    private void sendSmsMessage(Course course) {
        //1.设置发送消息内容
        MessageSmsDto messageSmsDto = new MessageSmsDto();
        messageSmsDto.setTitle("小太阳开课啦");
        messageSmsDto.setContent("亲爱的用户您好，最新课程 <a href='http://127.0.0.1:6002/detail.html?courseId='"+course.getId()+"''> "+course.getName()+" </a> 发布啦，点击课程了解详情");
        List<UserIdSmsDto> userIdSmsDtos = Arrays.asList(new UserIdSmsDto(1L, "789555"), new UserIdSmsDto(2L, "5454545"));
        //2.将数组中的用户数据存储到dto中
        messageSmsDto.setUsers(userIdSmsDtos);
        //3.使用mq单向发送消息
        rocketMQTemplate.sendOneWay(COURSE_SMS_TOPIC+":"+COURSE_SMS_TAG, JSON.toJSONString(messageSmsDto));

    }

    private Long saveCourse(Course course, List<Long> teacharIds) {
        //设置用户，参数
        course.setStatus(0);
        course.setLoginId(3L);
        course.setLoginUserName("13330964748");
        //2.通过老师id查询名字
        // 1.3.讲师需要查询之后进行讲师名称设置
        List<Teacher> teachers = teacherService.selectBatchIds(teacharIds);
        System.out.println(teachers);
        // 得到讲师名称使用逗号进行拼接
        String teacherStr = teachers.stream().map(Teacher::getName).collect(Collectors.joining(","));
        System.out.println(teacherStr);
        course.setTeacherNames(teacherStr);
        // 2.保存课程信息
        insert(course);
        return course.getId();
    }

    private Course selectByName(String name) {
        EntityWrapper<Course> wrapper = new EntityWrapper<>();
        wrapper.eq("name",name);
        return selectOne(wrapper);
    }


}
